package com.geetest.sdk.java.web.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.geetest.sdk.java.GeetestLib;
import com.yuexunit.finance.geetest.entity.GeetestSessionEntity;
import com.yuexunit.finance.geetest.service.GeetestSessionService;
import com.yuexunit.inject.ComponentFactory;

import net.sf.json.JSONObject;


/**
 * 使用Get的方式返回challenge和capthca_id,此方式以实现前后端完全分离的开发模式
 *
 */
public class StartCaptchaServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		GeetestSessionService geetestSessionService = ComponentFactory.loadClass(GeetestSessionService.class);
		GeetestSessionEntity geetest = new GeetestSessionEntity();
		GeetestLib gtSdk = new GeetestLib(GeetestConfig.getCaptcha_id(), GeetestConfig.getPrivate_key());
		
		String resStr = "{}";
		
		//自定义userid
		String userid = "test";

		//进行验证预处理
		int gtServerStatus = gtSdk.preProcess(userid);
		
		resStr = gtSdk.getResponseStr();
		//将服务器状态设置到session中
//		HttpSession session = request.getSession();
//		session.setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
//		//将userid设置到session中
//		session.setAttribute("userid", userid);
		geetest.setServerStatus(gtServerStatus);
		geetest.setServerStatusSessionKey(JSONObject.fromObject(resStr).getString("challenge"));
		geetest.setUserId(userid);
		geetestSessionService.createGeetestSession(geetest);

		PrintWriter out = response.getWriter();
		out.println(resStr);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}